//
//  HMCollectionViewCell.swift
//  EmotionKeybaord
//
//  Created by ZhuDong on 16/5/30.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

let totalCount = 21
let colCount = 7
let rowCount: CGFloat = 3
let cellMargin: CGFloat = 8
let windowOne = UIApplication.sharedApplication().windows.last
let emotionBtnDidClick = "emotionBtnDidClick"
class HMCollectionViewCell: UICollectionViewCell {
    var emotions:[HMEmotion]?{
        didSet{
            for (index,emotion) in (emotions?.enumerate())! {
                let btn = btns[index]
                btn.emotion = emotion
            }
        }
    }
    var btns:[HMEmotionButton] = [HMEmotionButton] ()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        self.addGestureRecognizer(gesture)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var popView: HMPopView = {
        let p = HMPopView()
        return p
    }()
    private func btnWithPoint(point: CGPoint)->HMEmotionButton?{
        for btn in btns{
            if btn.frame.contains(point) {
                    return btn
            }
        }
        return nil
    }
    @objc func longPress(gesture: UIGestureRecognizer){
        let point = gesture.locationInView(self.contentView)
        guard let btn = btnWithPoint(point) else{
            return
        }
        if btn.emotion!.isEmpty == true || btn.emotion!.isDelete == true {
            return
        }
        /*
        if gesture.state == .Began || gesture.state == .Changed {
            popView.show(btn)
        }else{
            popView.dismissAfter()
        }
        */
        switch gesture.state {
        case .Began,.Changed:
            popView.show(btn)
        default:
            popView.dismissAfter()
        }
    }
    func setupUI(){
        addBtns()
    }
    func addBtns(){
        let btnW = (contentView.bounds.size.width - 2 * cellMargin) / CGFloat(colCount)
        let btnH = (contentView.bounds.size.height - 30) / rowCount
        for index in 0..<totalCount {
            let btn = HMEmotionButton()
            let row = index / colCount
            let col = index % colCount
            let x = cellMargin + CGFloat(col) * btnW
            let y = CGFloat(row) * btnH
            btn.frame = CGRect(x: x, y: y, width: btnW, height: btnH)
            btns.append(btn)
            contentView.addSubview(btn)
            btn.addTarget(self, action: #selector(HMCollectionViewCell.btnClick(_:)), forControlEvents: .TouchUpInside)
        }
    }
    @objc private func btnClick(btn: HMEmotionButton){
        NSNotificationCenter.defaultCenter().postNotificationName(emotionBtnDidClick, object: btn.emotion)
    }
    
}
